package com.example.webfluxdemo;

import java.util.Objects;

import org.springframework.http.server.reactive.ServerHttpRequest;

public class IpUtils {
    private final static String ERROR_IP = "127.0.0.2";
    public static String getRequestIp(ServerHttpRequest request) {
        // 优先取 X-Real-IP
        String ip = request.getHeaders().getFirst("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("x-forwarded-for");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = Objects.requireNonNull(request.getRemoteAddress()).getHostName();
            if ("0:0:0:0:0:0:0:1".equals(ip)) {
                ip = ERROR_IP;
            }
        }
        if ("unknown".equalsIgnoreCase(ip)) {
            ip = ERROR_IP;
            return ip;
        }
        else if(ERROR_IP.equals(ip))
            return ip;

        int index = ip.indexOf(',');
        if (index >= 0) {
            ip = ip.substring(0, index);
        }

        return ip;
    }
}
